package aliyun.cx.admin.controller;

import aliyun.cx.admin.entity.Role;
import aliyun.cx.admin.service.RoleService;
import aliyun.cx.admin.dto.response.ApiResponse;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * 角色管理控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/admin/roles")
@RequiredArgsConstructor
public class RoleController {

    private final RoleService roleService;

    /**
     * 获取角色列表（分页）
     */
    @GetMapping("/list")
    @PreAuthorize("hasAuthority('PERM_ROLE_MANAGE')")
    public ApiResponse<Page<Role>> getRoleList(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String name,
            @RequestParam(required = false) Integer level) {
        
        try {
            Page<Role> rolePage = new Page<>(page, size);
            QueryWrapper<Role> wrapper = new QueryWrapper<>();
            
            if (name != null && !name.trim().isEmpty()) {
                wrapper.like("name", name.trim());
            }
            if (level != null) {
                wrapper.eq("level", level);
            }
            
            wrapper.orderByAsc("level", "name");
            roleService.page(rolePage, wrapper);
            
            return ApiResponse.success(rolePage);
        } catch (Exception e) {
            log.error("获取角色列表失败", e);
            return ApiResponse.error("获取角色列表失败: " + e.getMessage());
        }
    }

    /**
     * 获取角色详情
     */
    @GetMapping("/{id}")
    @PreAuthorize("hasAuthority('PERM_ROLE_MANAGE')")
    public ApiResponse<Role> getRoleById(@PathVariable Long id) {
        try {
            Role role = roleService.getById(id);
            if (role == null) {
                return ApiResponse.error("角色不存在");
            }
            return ApiResponse.success(role);
        } catch (Exception e) {
            log.error("获取角色详情失败，ID: {}", id, e);
            return ApiResponse.error("获取角色详情失败: " + e.getMessage());
        }
    }

    /**
     * 创建角色
     */
    @PostMapping("/create")
    @PreAuthorize("hasAuthority('role:write')")
    public ApiResponse<Role> createRole(@RequestBody Role role) {
        try {
            // 检查角色名称是否已存在
            if (roleService.existsByName(role.getName())) {
                return ApiResponse.error("角色名称已存在");
            }
            
            role.setCreateTime(LocalDateTime.now());
            role.setUpdateTime(LocalDateTime.now());
            
            boolean success = roleService.save(role);
            if (success) {
                return ApiResponse.success("角色创建成功", role);
            } else {
                return ApiResponse.error("角色创建失败");
            }
        } catch (Exception e) {
            log.error("创建角色失败", e);
            return ApiResponse.error("创建角色失败: " + e.getMessage());
        }
    }

    /**
     * 更新角色
     */
    @PutMapping("/{id}")
    @PreAuthorize("hasAuthority('role:write')")
    public ApiResponse<Role> updateRole(@PathVariable Long id, @RequestBody Role role) {
        try {
            Role existingRole = roleService.getById(id);
            if (existingRole == null) {
                return ApiResponse.error("角色不存在");
            }
            
            // 如果角色名称发生变化，检查新名称是否已存在
            if (!existingRole.getName().equals(role.getName()) && 
                roleService.existsByName(role.getName())) {
                return ApiResponse.error("角色名称已存在");
            }
            
            role.setId(id);
            role.setUpdateTime(LocalDateTime.now());
            role.setCreateTime(existingRole.getCreateTime()); // 保持原创建时间
            
            boolean success = roleService.updateById(role);
            if (success) {
                return ApiResponse.success("角色更新成功", role);
            } else {
                return ApiResponse.error("角色更新失败");
            }
        } catch (Exception e) {
            log.error("更新角色失败，ID: {}", id, e);
            return ApiResponse.error("更新角色失败: " + e.getMessage());
        }
    }

    /**
     * 删除角色
     */
    @DeleteMapping("/{id}")
    @PreAuthorize("hasAuthority('role:delete')")
    public ApiResponse<String> deleteRole(@PathVariable Long id) {
        try {
            Role role = roleService.getById(id);
            if (role == null) {
                return ApiResponse.error("角色不存在");
            }
            
            boolean success = roleService.removeById(id);
            if (success) {
                return ApiResponse.success("角色删除成功");
            } else {
                return ApiResponse.error("角色删除失败");
            }
        } catch (Exception e) {
            log.error("删除角色失败，ID: {}", id, e);
            return ApiResponse.error("删除角色失败: " + e.getMessage());
        }
    }

    /**
     * 为角色分配权限
     */
    @PostMapping("/{id}/permissions")
    @PreAuthorize("hasAuthority('role:write')")
    public ApiResponse<String> assignPermissions(
            @PathVariable Long id, 
            @RequestBody Map<String, List<Long>> request) {
        
        try {
            Role role = roleService.getById(id);
            if (role == null) {
                return ApiResponse.error("角色不存在");
            }
            
            List<Long> permissionIds = request.get("permissionIds");
            boolean success = roleService.assignPermissions(id, permissionIds);
            
            if (success) {
                return ApiResponse.success("权限分配成功");
            } else {
                return ApiResponse.error("权限分配失败");
            }
        } catch (Exception e) {
            log.error("分配角色权限失败，角色ID: {}", id, e);
            return ApiResponse.error("分配权限失败: " + e.getMessage());
        }
    }

    /**
     * 获取角色的权限列表
     */
    @GetMapping("/{id}/permissions")
    @PreAuthorize("hasAuthority('PERM_ROLE_MANAGE')")
    public ApiResponse<List<Long>> getRolePermissions(@PathVariable Long id) {
        try {
            Role role = roleService.getById(id);
            if (role == null) {
                return ApiResponse.error("角色不存在");
            }
            
            List<Long> permissionIds = roleService.getPermissionIdsByRoleId(id);
            return ApiResponse.success(permissionIds);
        } catch (Exception e) {
            log.error("获取角色权限失败，角色ID: {}", id, e);
            return ApiResponse.error("获取角色权限失败: " + e.getMessage());
        }
    }

    /**
     * 获取所有角色（不分页，用于下拉选择）
     */
    @GetMapping("/all")
    @PreAuthorize("hasAuthority('PERM_ROLE_MANAGE')")
    public ApiResponse<List<Role>> getAllRoles() {
        try {
            QueryWrapper<Role> wrapper = new QueryWrapper<>();
            wrapper.orderByAsc("level", "name");
            List<Role> roles = roleService.list(wrapper);
            return ApiResponse.success(roles);
        } catch (Exception e) {
            log.error("获取所有角色失败", e);
            return ApiResponse.error("获取所有角色失败: " + e.getMessage());
        }
    }
}